import {post} from '../../utils/axios'
import {setLocalStorage} from '../../utils/localStorage'
import router from '../../router/index'
const state = {
  token: null,
  title: '',
  user: '',
  valid: null,
  showApp: false,
  username: '',
  password: '',
  usernameRules: [
    (v) => !!v || '请输入用户名'
  ],
  passwordRules: [
    (v) => !!v || '请输入密码'
  ],
  alert: false,
  msg: null
}

const mutations = {
  login: (state, payload) => {
    if (payload.validate()) {
      post('/api/token/', {
        username: state.username,
        password: state.password
      }).then((response) => {
        setLocalStorage('admin-token', response['access'], 0.5)
        router.replace({ path: '/dashboard' })
      }).catch((error) => {
        console.log(error)
        state.alert = true
        state.msg = '用户名或密码错误！'
      })
    }
  },
  clearLogin: (state, payload) => {
    payload.reset()
    state.alert = false
  },
  downLoadApp: (state) => {
    let r = confirm('1、目前数据中心网络无法直接访问，手机版只能访问测试环境！\n2、由于没有ios开发环境，目前只有安卓版!')
    if (r === true) {
      window.location.href = 'http://10.42.0.18/sftp/app/android/cmdb.apk'
    }
  }
}

const actions = {
  login: ({commit}, payload) => {
    commit('login', payload)
  },
  clearLogin: ({commit}, payload) => {
    commit('clearLogin', payload)
  },
  downLoadApp: ({commit}) => {
    commit('downLoadApp')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
